package com.yjd.back.job;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.yjd.comm.annotation.ServiceRemoteProxy;
import com.yjd.comm.base.control.BaseControl;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.base.model.PagerHtmlModel;
import com.yjd.comm.base.model.ResultModel;
import com.yjd.comm.enums.RpcJobExecStatus;
import com.yjd.job.model.JobModel;
import com.yjd.job.service.IJobLogService;
import com.yjd.job.service.IJobRemoteService;
import com.yjd.job.service.IJobService;
import com.yjd.comm.rpm.RpmServiceKeyEnum;
import com.yjd.comm.system.dto.AdminDataWrap;
import com.yjd.comm.system.util.AdminDataUtil;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.PagerUtil;
import com.yjd.comm.util.ServletUtil;
import com.yjd.comm.vo.Constant.ResultEnum;

/**
 * @Description: TODO
 * @author SongJian devpage@126.com
 * @date 2015-4-28
 */
@Scope("prototype")
@Controller
@RequestMapping(value = "/job")
public class JobControl extends BaseControl {

	@ServiceRemoteProxy(serviceUrlResouceKey = RpmServiceKeyEnum.RPM_BI_JOB_SERVICE_KEY)
	IJobRemoteService jobRemoteService;

	@ServiceRemoteProxy(serviceUrlResouceKey = RpmServiceKeyEnum.RPM_JOB_SERVICE_KEY)
	IJobService jobService;

	@ServiceRemoteProxy(serviceUrlResouceKey = RpmServiceKeyEnum.RPM_JOB_SERVICE_KEY)
	IJobLogService jobLogService;

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/defined_list")
	public String monitor(HttpServletRequest request) throws Exception
	{
		List<JobModel> definedJobs = this.jobService.getModelList(
				FrameUtil.newHashMap("typeLike", "com.yjd.bi"), DbWREnums.READ);
		request.setAttribute("definedJobs", definedJobs);
		return "job.defined_list.jsp";
	}

	/*@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(HttpServletRequest request) throws Exception
	{
		return "add.job.jsp";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public void addPost(HttpServletRequest request, @Valid JobModel jobModel, BindingResult result) throws Exception
	{
		if (result.hasErrors())
		{
			String err_msg = result.getFieldError().getDefaultMessage();
			super.errorMsg(null, err_msg);
			return;
		}

		// 添加附属属性
		jobModel.setCreate_time(FrameUtil.getTime(null));
		AdminDataWrap loginAdmin = AdminDataUtil.getAdminDataWrap(request, response);
		jobModel.setId_user_create(loginAdmin.getAdminModel().getAdmin_id());

		ResultModel resultModel = jobService.insert(jobModel);
		if (resultModel.getResult().ordinal() == ResultEnum.SUCCESS.ordinal())
		{
			super.successMsg(ServletUtil.getUrl("/job/defined_list", null), "添加成功");
		} else
		{
			this.errorMsg(null, resultModel.getMessage());
		}
	}*/

	@RequestMapping(value = "/update/{id_job}", method = RequestMethod.GET)
	public String updatePage(HttpServletRequest request, @PathVariable("id_job") Long id_job) throws Exception
	{
		JobModel jobModel = jobService.getModelById(id_job,DbWREnums.READ);
		request.setAttribute("jobModel", jobModel);
		return "update.job.jsp";
	}

	@RequestMapping(value = "/update")
	public void update(HttpServletRequest request, @Valid JobModel jobModel, BindingResult result) throws Exception
	{
		if (result.hasErrors())
		{
			String err_msg = result.getFieldError().getDefaultMessage();
			super.errorMsg(null, err_msg);
			return;
		}
		jobModel.setModify_time(FrameUtil.getTime(null));
		AdminDataWrap loginAdmin = AdminDataUtil.getAdminDataWrap(request, response);
		jobModel.setId_user_modify(loginAdmin.getAdminModel().getAdmin_id());

		ResultModel resultModel = jobService.update(jobModel);
		if (resultModel.getResult().ordinal() == ResultEnum.SUCCESS.ordinal())
		{
			super.successMsg(ServletUtil.getUrl("/job/defined_list", null), "更新成功");
		} else
		{
			this.errorMsg(null, resultModel.getMessage());
		}
	}

	@RequestMapping(value = "/call/{id_job}")
	public void call(HttpServletRequest request, @PathVariable("id_job") Long id_job) throws Exception
	{
		JobModel jm = jobService.getModelById(id_job,DbWREnums.READ);
		int call_result = jobRemoteService.call(jm.getType());
		if (call_result == RpcJobExecStatus.SUCCESS.getValue())
		{
			this.successMsg("调用成功");
		} else
		{
			if(call_result==-999){
				this.errorMsg(null,"该JOB的实例不存在");
			}else{
				this.errorMsg(null,RpcJobExecStatus.getDesc(call_result));
			}
			
		}

	}

	@RequestMapping(value = "/failed_jobs")
	public String failedJobs(HttpServletRequest request) throws Exception
	{
		Map paramMap = ServletUtil.getPageParameterMap(request);
		String page = request.getParameter("page");
		paramMap.put("page", StringUtils.isEmpty(page)?1:page);
		request.setAttribute("page", page);
		String rows = request.getParameter("rows");
		paramMap.put("rows", StringUtils.isEmpty(rows)?20:rows);
		paramMap.put("sort","a.end_time desc");
		/*Calendar today_calendar = Calendar.getInstance();
		if (!paramMap.containsKey("search_start_time")
				|| StringUtils.isEmpty(paramMap.get("search_start_time").toString()))
		{
			paramMap.put("search_start_time", DateUtil.dateStringToTimestamp(new SimpleDateFormat(
					DateUtil.PATTERN_yyyy_MM_dd).format(today_calendar.getTime()), DateUtil.PATTERN_yyyy_MM_dd));
		}
		today_calendar.add(Calendar.DATE, 1);
		if (!paramMap.containsKey("search_end_time") || StringUtils.isEmpty(paramMap.get("search_end_time").toString()))
		{
			paramMap.put("search_end_time", DateUtil.dateStringToTimestamp(new SimpleDateFormat(
					DateUtil.PATTERN_yyyy_MM_dd).format(today_calendar.getTime()), DateUtil.PATTERN_yyyy_MM_dd));
		}*/
		PagerHtmlModel pager = PagerUtil.getPagerHtmlModel(jobLogService.getFailedJobLogPage(paramMap), paramMap,
				ServletUtil.getUrl("/job/failed_jobs"));
		request.setAttribute("pager", pager);
		return "failed.job.jsp";
	}

}
